package com.yxn.cloud.product.web;

import com.alibaba.fastjson.JSONObject;
import com.yxn.cloud.product.entity.CategoryEntity;
import com.yxn.cloud.product.service.CategoryService;
import com.yxn.cloud.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * @author lisw
 * @create 2021/7/3 16:38
 */
@Controller
public class IndexController {

    @Resource
    private CategoryService categoryService;

    @Resource
    RedissonClient redissonClient;

    @GetMapping({"/","/index"})
    public String toIndex(Model model){
        /**获取一级菜单*/
        List<CategoryEntity> level1 = categoryService.selectLevel1Category();
        model.addAttribute("categorys", level1);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson() throws InterruptedException {
        Map<String, List<Catalog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello() throws InterruptedException {
        //获取一把锁，只要锁的名字一样，就会是同一把锁
        RLock lock = redissonClient.getLock("lock");

        //显式加锁 此时是一种阻塞式等待，无需进行睡眠，只有获取到锁时，才会执行
        lock.lock();
        try {
            Thread.sleep(3000L);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("出错了");
        }finally{
            lock.unlock();
        }
        return "hello";
    }
}
